import React, { useState, useEffect } from 'react';
import { Button, Form, Input, Modal, message } from 'antd';
import { CheckCircleOutlined,LoadingOutlined,CheckCircleTwoTone,ExclamationCircleTwoTone } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import './index.scss'
import { addAccount, getKey, createUrl,UrlState } from '../../api';
const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
};
var timer:NodeJS.Timeout
//输入框规则
const validateMessages = {
  required: '${label}是必填项',
};
const Account: React.FC = () => {
  const navgitate = useNavigate()
  const [modal, contextHolder] = Modal.useModal();
  const [loadings, setLoadings] = useState<boolean[]>([]);
  const [key, setKey] = useState('')
  const [qrUrl, setQrurl] = useState('')
  const [qrState, setQrstate] = useState(0)
  const [cookie, setCookie] = useState('')
  const [nickName,setNickName] = useState('')
  function changeLoading(index: number) {
    setLoadings((prevLoadings) => {
      const newLoadings = [...prevLoadings];
      const nowLoading = newLoadings[index]
      newLoadings[index] = !nowLoading;
      return newLoadings;
    });
  }
  const confirm = () => {
    modal.confirm({
      title: '开通成功',
      icon: <CheckCircleOutlined style={{ color: '#52c41a' }} />,
      content: '开通账号成功是否跳转到账号列表配置账号(默认配置可能并不适用与你的账号)',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        navgitate('/home/accounts')
        window.location.reload()
      }
    });
  };
  const enterLoading = (index: number, values: any) => {
    console.log(cookie)
    if (qrState !== 4) return message.warning('请使用网易云音乐App扫码登录')
    changeLoading(index)
    addAccount(values.key,cookie,nickName).then(res => {
      if (res.data.code) {
        changeLoading(index)
        confirm()
      } else {
        changeLoading(index)
        message.error(res.data.msg, 3)
      }
    })

  };
  //生成key并创建二维码
  function createQrcode() { 
    setQrstate(1)
    getKey().then(res => {
      if (res.data.msg.body.code === 200) {
        setKey(res.data.msg.body.data.unikey)
        qrCreate(res.data.msg.body.data.unikey)
        getUrlState(res.data.msg.body.data.unikey)
      } else {
        message.warning('二维码生成异常，请稍后重试')
      }
    })
  }
  //生成登录key
  useEffect(() => {
    createQrcode()
    return clearInterval(timer)
  }, [])
  //轮询登录状态
  function getUrlState(key:string) { 
    timer = setInterval(() => { 
      UrlState(key).then(res => { 
        const { code} = res.data.msg?.body||3
        switch (code) {
          case 800:
            setQrstate(3)
            clearInterval(timer)
            break;
          case 802:
            setNickName(res.data.msg.body.nickname)
            setQrstate(2)
            break
          case 803:
            setQrstate(4)
            clearInterval(timer)
            setCookie(res.data.msg.body.cookie)
            break
          default:
            break;
        }
      })
    },1000)  
  }
  //获取二维码地址
  async function qrCreate(keys = key) {
    const { data } = await createUrl(keys)
    if ((data.code) === 0) return message.warning('二维码生成异常，请稍后重试')
    setQrurl(data.msg.body.data.qrimg)
    setQrstate(0)
  }
  return (
    <div className='add-acc'>
      {contextHolder}
      <Form
        {...layout}
        name="nest-messages"
        onFinish={(e) => { enterLoading(0, e) }}
        style={{ maxWidth: 600 }}
        validateMessages={validateMessages}
        labelAlign='right'
      >
        <Form.Item name='login' label="二维码登录">
          <div className='qrurl-box'>
            <div className='remind' style={{ display: qrState !== 0 ? 'flex' : 'none' }}>
              {/* 为1时为等待 */}
              <LoadingOutlined style={{ display: qrState === 1 ? 'inline-block' : 'none' }}></LoadingOutlined>
              {/* 为2时为已扫描 */}
              <div className='scanned' style={{ display: qrState === 2 ? 'flex' : 'none' }}>
                <CheckCircleTwoTone twoToneColor="#52c41a" style={{ fontSize: 20 }} />
                <p>已扫描，待确认</p>
              </div>
              {/* 为3时为超时 */}
              <div className='scanned' onClick={createQrcode} style={{ display: qrState === 3 ? 'flex' : 'none' }}>
                <ExclamationCircleTwoTone twoToneColor="red" style={{ fontSize: 20 }} />
                <p>超时，点击刷新</p>
              </div>
              {/* 为4时登录成功 */}
              <div className='scanned' style={{ display: qrState === 4 ? 'flex' : 'none' }}>
                <CheckCircleTwoTone twoToneColor="#52c41a" style={{ fontSize: 20 }} />
                <p>登录成功</p>
              </div>
            </div>
            <img src={ qrUrl} alt="" />
          </div>
        </Form.Item>
        <Form.Item name='key' label="卡密" rules={[{ required: true }]}>
          <Input></Input>
        </Form.Item>
        <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
          <Button type="primary" htmlType="submit" loading={loadings[0]} >
            添加
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}

export default Account;